import os.path
import re

from app.db.archive_oper import ArchiveOper
from app.plugins import _PluginBase
from typing import Any, List, Dict, Tuple
from app.core.event import eventmanager, Event
from app.schemas.types import EventType
from app.db.category_oper import CategoryOper

from app.db.tag_group_oper import TagGroupOper
from app.db.tag_oper import TagOper


def parse(content, field):
    pattern = rf'{field}:\s+(.*)'
    match = re.search(pattern, content, re.IGNORECASE)
    if match is not None:
        return match.group(1)



class GalleryInfo(_PluginBase):
    plugin_name: str = 'gallery_info'
    plugin_icon: str = 'gallery_info.png'
    plugin_desc: str = '支持识别档案中的gallery_info.txt中的metadata'
    plugin_ver: str = '1.0.0'
    url: str = 'url'
    author: str = 'BugGeeker'
    # 插件配置项ID前缀
    plugin_config_prefix = "gallery_info_"

    _enabled: bool = True

    def __init__(self):
        super().__init__()
        self.tag_group_oper = TagGroupOper()
        self.tag_oper = TagOper()
        self.category_oper = CategoryOper()
        self.archive_oper = ArchiveOper()

    def init_plugin(self, config: dict = None):
        print(f"GalleryInfo插件加载成功, config: {config}")
        if config:
            self._enabled = config.get("enabled")

    def get_state(self) -> bool:
        return self._enabled

    @staticmethod
    def get_command() -> List[Dict[str, Any]]:
        pass

    def get_api(self) -> List[Dict[str, Any]]:
        pass

    def get_page(self) -> List[dict]:
        pass

    def get_form(self) -> Tuple[List[dict], Dict[str, Any]]:
        pass

    def read_gallery_info(self, path):
        path = f'{path}/galleryinfo.txt'
        print(path)
        # 判断galleryinfo.txt是否存在
        if os.path.exists(path):
            with open(path, 'r') as file:
                txt_content = file.read()
                keys = ["Title", "Upload Time", "Uploaded By", "Downloaded", "Tags", "Category", "raw"]
                json = {}
                for key in keys:
                    value = parse(txt_content, key)
                    if value is not None:
                        if key == 'Tags':
                            tags = value.split(",")
                            tags_id = []
                            for tag in tags:
                                tag = tag.strip()
                                [group_name, tag_name] = tag.split(":")
                                # 判断group是否已存在
                                find_group = self.tag_group_oper.get_by_name(group_name)
                                if find_group is None:
                                    group_id = self.tag_group_oper.add(group_name)
                                else:
                                    group_id = find_group.id
                                # 判断tag是否已存在
                                find_tag = self.tag_oper.get_by_name(tag_name)
                                if find_tag is None:
                                    tag_id = self.tag_oper.add(name=tag_name, full_name=tag, group_id=group_id)
                                else:
                                    tag_id = find_tag.id
                                tags_id.append(tag_id)
                            json['tags_id'] = ','.join(str(x) for x in tags_id)
                        elif key == 'Category':
                            # 判断category是否已存在
                            find_category = self.category_oper.get_by_name(value)
                            if find_category is None:
                                category_id = self.category_oper.add(value)
                            else:
                                category_id = find_category.id
                            json['category_id'] = category_id
                        else:
                            json[key] = value
                    else:
                        json[key] = ''
                return json
        else:
            print("galleryinfo.txt不存在")

    @eventmanager.register(EventType.ArchiveAdded)
    def parse_gallery_info(self, event: Event):
        print("使用GalleryInfo插件解析档案")
        print(f"event: {event.event_data}")
        try:
            data = self.read_gallery_info(event.event_data['unpack_path'])
            json = {
                "title": data['Title'],
                "upload_time": data['Upload Time'],
                "upload_by": data['Uploaded By'],
                "url": data['raw'],
                "categories_id": data['category_id'],
                "tags_id": data['tags_id'],
            }
            print(f"更新archive{json}")
            archive = self.archive_oper.update(archive_id=event.event_data['id'], payload=json)
            print(archive)
        except Exception as e:
            print(e)

    def stop_service(self):
        """
        退出插件
        """
        pass
